package com.example.gsq.news.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Toast;

import com.example.gsq.news.R;
import com.example.gsq.news.adapter.NewsAdapter;
import com.example.gsq.news.base.BaseActivity;
import com.example.gsq.news.base.BaseFragment;
import com.example.gsq.news.bean.News;
import com.example.gsq.news.ui.activity.NewsContentActivity;
import com.example.gsq.news.util.C;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

public class NewsFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener{

    private LinearLayout mEmptyLayout;

    private SwipeRefreshLayout mSwipeLayout;

    private RecyclerView mRecyclerView;
    private List<News> mNewsList;
    private NewsAdapter mAdapter;

    private View view;

    private String urlString;

    private NetStateBroadcastReceiver mNetReceiver;

    public NewsFragment() {

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        this.urlString = getArguments().getString("fragmentUrl");
        initViews();

        if (BaseActivity.isNetworkAvailable(mActivity)) {
            doAsyncTask(C.TaskId.FRAGMENT_GET_JSON_LIST, urlString);
        } else {
            mRecyclerView.setVisibility(View.GONE);
            mEmptyLayout.setVisibility(View.VISIBLE);
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mNetReceiver = new NetStateBroadcastReceiver();
        mActivity.registerReceiver(mNetReceiver, filter);

    }


    private void initViews() {
        mEmptyLayout = (LinearLayout) view.findViewById(R.id.layout_nonet);

        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_layout);
        mSwipeLayout.setColorSchemeResources(R.color.colorPrimary);
        mSwipeLayout.setOnRefreshListener(this);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.fragment_recycler);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(mActivity);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mNewsList = new ArrayList<>();
        mAdapter = new NewsAdapter(this, mNewsList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new NewsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String contentUrl = mNewsList.get(position).getContentUrl();
                mActivity.forward(NewsContentActivity.class, contentUrl);
            }
        });
        mAdapter.setOnLoadMoreListener(new NewsAdapter.OnLoadMoreListener() {
            @Override
            public void startLoadMore() {
                if(BaseActivity.isNetworkAvailable(mActivity)){
                    doAsyncTask(C.TaskId.FRAGMENT_GET_JSON_LIST, C.TaskType.TASK_PULL_LOADMORE, urlString);
                } else {
                    Toast.makeText(mActivity, "网络连接不可用，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            }
        });

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                mSwipeLayout.setEnabled(topRowVerticalPosition >= 0);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        mEmptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mEmptyLayout.getVisibility() == View.VISIBLE){
                    if(BaseActivity.isNetworkAvailable(mActivity)){
                        mSwipeLayout.setRefreshing(true);
                        doAsyncTask(C.TaskId.FRAGMENT_GET_JSON_LIST, C.TaskType.TASK_PULL_REFRESH, urlString);
                    } else {
                        Toast.makeText(mActivity, "网络连接不可用，请稍后重试", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onTaskComplete(int taskId, int taskType, Bitmap bitmap, String imageUrl) {
        super.onTaskComplete(taskId, taskType, bitmap, imageUrl);
        if (taskId == C.TaskId.FRAGMENT_GET_ITEM_BITMAP) {
            ImageView imageView = (ImageView) mRecyclerView.findViewWithTag(imageUrl);
            if (imageView != null && bitmap != null && imageUrl!= null) {
                imageView.setImageBitmap(bitmap);
                mAdapter.getLruCache().put(imageUrl, bitmap);
            }
        }
    }

    @Override
    public void onTaskComplete(int taskId, int taskType, String responseString) {
        super.onTaskComplete(taskId, taskType, responseString);
        adjustViews();
        parserJSONString(responseString, taskType);
        mAdapter.notifyDataSetChanged();
        mAdapter.loadImageWhenStopScroll();
        mSwipeLayout.setRefreshing(false);
    }

    private void adjustViews() {
        if (mRecyclerView.getVisibility() == View.GONE) {
            mRecyclerView.setVisibility(View.VISIBLE);
            mEmptyLayout.setVisibility(View.GONE);
        }
    }

    private void parserJSONString(String jsonString, int taskType) {
        try {
            List<News> tempList = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject resultJSON = jsonObject.getJSONObject("result");
            JSONArray dataArray = resultJSON.getJSONArray("data");
            for (int i = 0; i < dataArray.length(); i++) {
                String title = ((JSONObject) dataArray.get(i)).getString("title");
                String imageUrl = ((JSONObject) dataArray.get(i)).getString("thumbnail_pic_s");
                String contentUrl = ((JSONObject) dataArray.get(i)).getString("url");
                String newsDate = ((JSONObject) dataArray.get(i)).getString("date");
                News news = new News(title, null, contentUrl, imageUrl, newsDate);
                tempList.add(news);
            }
            switch (taskType) {
                case C.TaskType.TASK_PULL_REFRESH:
                    mNewsList.clear();
                    mNewsList.addAll(tempList);
                    break;
                case C.TaskType.TASK_PULL_LOADMORE:
                    mNewsList.addAll(tempList);
                    break;
                default:
                    break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRefresh() {
        mSwipeLayout.setRefreshing(true);
        if (BaseActivity.isNetworkAvailable(mActivity)) {
            doAsyncTask(C.TaskId.FRAGMENT_GET_JSON_LIST, C.TaskType.TASK_PULL_REFRESH, urlString);
        } else {
            if (mRecyclerView.getVisibility() == View.VISIBLE) {
                mRecyclerView.setVisibility(View.GONE);
                mEmptyLayout.setVisibility(View.VISIBLE);
            }
            mSwipeLayout.setRefreshing(false);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(mNetReceiver);
    }

    class NetStateBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager netConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = netConnectivityManager.getActiveNetworkInfo();
                if (info != null) {
//                    Toast.makeText(context, "当前网络类型：" + info.getTypeName(), Toast.LENGTH_SHORT).show();
                    if(mRecyclerView.getVisibility() == View.VISIBLE || mSwipeLayout.isRefreshing()){
                        doAsyncTask(C.TaskId.FRAGMENT_GET_JSON_LIST, C.TaskType.TASK_PULL_REFRESH, urlString);
                    }
                } else {
//                    Toast.makeText(context, "网络连接不可用，请稍后重试", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}
